package cn.lyx.xiaohoshu.auth.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.lyx.framework.common.exception.BizException;
import cn.lyx.framework.common.response.Response;
import cn.lyx.xiaohoshu.auth.contants.RedisKeyConstants;
import cn.lyx.xiaohoshu.auth.enums.ResponseCodeEnum;
import cn.lyx.xiaohoshu.auth.model.vo.verificationcode.SendVerificationCodeReqVO;
import cn.lyx.xiaohoshu.auth.service.VerificationCodeService;
import cn.lyx.xiaohoshu.auth.sms.AliyunSmsHelper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;

/**
 * @Author by lyx
 */
@Service
@Slf4j
public class VerificationCodeServiceImpl implements VerificationCodeService {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private AliyunSmsHelper aliyunSmsHelper;
    @Resource(name = "taskExecutor")
    private Executor taskExecutor;

    @Override
    public Response<?> send(SendVerificationCodeReqVO sendVerificationCodeReqVO) {

        String phone = sendVerificationCodeReqVO.getPhone();

        // build redis key
        String redisKey = RedisKeyConstants.buildVerificationCodeKey(phone);

        // 判断是否发送验证码
        if (Boolean.TRUE.equals(redisTemplate.hasKey(redisKey))) {
            throw new BizException(ResponseCodeEnum.VERIFICATION_CODE_SEND_FREQUENTLY);
        }

        // 未发送 则生成 6 位随机数验证码
        String verificationCode = RandomUtil.randomNumbers(6);

        log.info("手机号：{}， 发送验证码：{}", phone, verificationCode);

        // 调用第三方短信服务
//        taskExecutor.execute(() -> {
//            String signName = "阿里云短信测试";
//            String templateCode = "SMS_154950909";
//            String templateParam = String.format("{\"code\":\"%s\"}", verificationCode);
//            aliyunSmsHelper.sendMessage(signName, templateCode, phone, templateParam);
//        });

        // 存入 redis
        redisTemplate.opsForValue().set(redisKey, verificationCode, 3, TimeUnit.MINUTES);

        return Response.success();
    }
}
